package com.ahao.aggregation;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.widget.Toast;

import com.ahao.abstraction.IChannel;
import com.ahao.abstraction.ILifeCycle;
import com.ahao.abstraction.LoginResult;
import com.ahao.abstraction.PayParams;
import com.ahao.abstraction.ISDKListener;
import com.ahao.abstraction.RoleInfoParams;
import com.ahao.aggregation.bean.LocalConfig;
import com.ahao.aggregation.bean.MetaDataConfig;
import com.ahao.aggregation.entry.UserInfo;
import com.ahao.aggregation.utils.ChannelFactory;
import com.ahao.aggregation.utils.ConfigBuilder;
import com.ahao.aggregation.utils.ConfigUtils;
import com.ahao.aggregation.utils.LogUtils;
import com.ahao.aggregation.utils.MetaDataUtils;
import com.ahao.aggregation.utils.SimpleHttpGetRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Properties;

public class AHSDKManager implements IChannel {
    private static AHSDKManager instance;
    private Activity mActivity;
    private Context mContext;
    private IChannel channel;

    private LocalConfig localConfig;
    private ISDKListener mISDKListener;
    /**
     * 生命周期未注册时候防止崩溃
     */
    private ILifeCycle defaultLifeCycle = new DefaultLifeCycle();
    private MetaDataConfig metaDataConfig;

    public static AHSDKManager getInstance() {
        if (instance == null) {
            instance = new AHSDKManager();
        }
        return instance;
    }

    @Override
    public void login(Context context) {
        mContext = context;
        if (getChannel() != null) {
            getChannel().login(context);
        } else {
            LogUtils.error("请先初始化");
        }
    }



    @Override
    public void pay(Context context, PayParams payParams) {
        mContext = context;
        if (getChannel() != null) {
            platformGetOrderId(context, payParams);
        } else {
            LogUtils.error("请先初始化");
        }
    }

    private void platformGetOrderId(Context context, PayParams payParams) {
        SimpleHttpGetRequest httpRequest = new SimpleHttpGetRequest(new SimpleHttpGetRequest.OnHttpRequestCompleteListener() {
            @Override
            public void onHttpRequestComplete(String result) {
                // 在这里处理 HTTP 请求的结果
                try {
                    if (result != null) {
                        // 处理成功的情况
                        // result 包含服务器响应的内容
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        String msg = jsonObject.getString("msg");
                        if (code == CONSTANT.SUCCESS) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            String orderid = data.getString("orderid");
                            payParams.orderid = orderid;
                            getChannel().pay(context, payParams);
                        } else {
                            mISDKListener.onPayResult(CONSTANT.ERROR, msg);
                        }
                    } else {
                        // 处理失败的情况
                        mISDKListener.onPayResult(CONSTANT.ERROR, "平台下单失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mISDKListener.onPayResult(CONSTANT.ERROR, "平台下单发生异常：" + e.getMessage());
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                httpRequest.execute("/v1.jh_get_order_id", payParams);
            }
        }).start();
    }

    @Override
    public void init(Activity activity, ISDKListener isdkListener) {
        mActivity = activity;
        mContext = activity;
        try {
            // 类反射
            LogUtils.info("当前渠道名：" + getLocalConfig(mContext).getChannel());
            metaDataConfig = MetaDataUtils.createInstanceFromMetaData(mContext, MetaDataConfig.class);
            SimpleHttpGetRequest.extParams = String.format("&channel=%s&%s", getLocalConfig(mContext).getChannel(), SimpleHttpGetRequest.handleParams(getMetaDataConfig()));
            SimpleHttpGetRequest.HOST = getLocalConfig(mContext).getHost();
            mISDKListener = new ISDKListener() {
                @Override
                public void onLoginResult(int code, Object result) {
                    if (code == CONSTANT.SUCCESS) {
                        LoginResult res = (LoginResult) result;
                        if (res.isVerify) {
                            getThirdUid(activity, res, isdkListener);
                        } else {
                            completeLogin(activity, res, isdkListener);
                        }
                    } else {
                        isdkListener.onLoginResult(code, result);
                    }
                }

                @Override
                public void onInitResult(int code, String msg) {
                    isdkListener.onInitResult(code, msg);
                }

                @Override
                public void onPayResult(int code, String msg) {
                    isdkListener.onPayResult(code, msg);
                }

                @Override
                public void onCustomEvent(int type, HashMap data) {
                    isdkListener.onCustomEvent(type, data);

                }

                @Override
                public void onLogoutResult(int code, Object result) {
                    isdkListener.onLogoutResult(code, result);

                }
            };
            LogUtils.info(getLocalConfig(mContext).getChannel() + " channel load");
            getChannel().init(activity, mISDKListener);
        } catch (Exception e) {
            LogUtils.error("channel load error:" + e.getMessage());
        }
    }

    private void getThirdUid(Context context, LoginResult res, ISDKListener isdkListener) {
        SimpleHttpGetRequest httpRequest = new SimpleHttpGetRequest(new SimpleHttpGetRequest.OnHttpRequestCompleteListener() {
            @Override
            public void onHttpRequestComplete(String result) {
                // 在这里处理 HTTP 请求的结果
                try {
                    if (result != null) {
                        // 处理成功的情况
                        // result 包含服务器响应的内容
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        String msg = jsonObject.getString("msg");
                        if (code == CONSTANT.SUCCESS) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            // 渠道的校验后的结果可能要返回一些token或者 userid 另用,大多数都是返回字符串
                            Object defautCuserid = data.get("cuserid");
                            if (res.getValidationInterceptor() != null) {
                                defautCuserid = res.getValidationInterceptor().onInterceptor(defautCuserid);
                            }
                            res.setUsername(defautCuserid.toString());
                            completeLogin(context, res, isdkListener);
                        } else {
                            isdkListener.onLoginResult(CONSTANT.ERROR, msg);
                        }
                    } else {
                        // 处理失败的情况
                        isdkListener.onLoginResult(CONSTANT.ERROR, "网络请求失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理失败的情况
                    isdkListener.onLoginResult(CONSTANT.ERROR, "发生异常：" + e.getMessage());
                }
            }
        });
        String loginResultParams = String.format("username=%s&uid=%s&token=%s", res.getUsername(), res.getUserId(), res.getToken());
        new Thread(new Runnable() {
            @Override
            public void run() {
                httpRequest.execute("/v1.jh_get_third_uid", res);
            }
        }).start();
    }

    private void completeLogin(Context context, LoginResult res, ISDKListener isdkListener) {
        SimpleHttpGetRequest httpRequest = new SimpleHttpGetRequest(new SimpleHttpGetRequest.OnHttpRequestCompleteListener() {
            @Override
            public void onHttpRequestComplete(String result) {
                // 在这里处理 HTTP 请求的结果
                try {
                    if (result != null) {
                        // 处理成功的情况
                        // result 包含服务器响应的内容
                        JSONObject jsonObject = new JSONObject(result);
                        int code = jsonObject.getInt("code");
                        String msg = jsonObject.getString("msg");
                        if (code == CONSTANT.SUCCESS) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            res.setUsername(data.getString("username"));
                            res.setUserId(data.getString("uid"));
                            LogUtils.info("token:" + data.getString("token"));
                            res.setToken(data.getString("token"));
                            UserInfo.getInstance().setLoginResult(res);
                            isdkListener.onLoginResult(CONSTANT.SUCCESS, res);
                            if (getLocalConfig(context).getChannel().equals("aggregation")) {
                                AHSDKManager.showToast(context, "登录成功");
                                AHAOUiManager.getInstance().showFloatView(context);
                            }
                        } else {
                            isdkListener.onLoginResult(CONSTANT.ERROR, msg);
                        }
                    } else {
                        // 处理失败的情况
                        isdkListener.onLoginResult(CONSTANT.ERROR, "网络请求失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    // 处理失败的情况
                    isdkListener.onLoginResult(CONSTANT.ERROR, "发生异常：" + e.getMessage());
                }
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                httpRequest.execute("/v1.jh_third_login", res);
            }
        }).start();
    }

    @Override
    public void uploadRoleInfo(Context context, RoleInfoParams roleInfoParams) {
        if (getChannel() != null) {
            String roleName = roleInfoParams.roleName;
            String roleId = roleInfoParams.roleId;
            String serverName = roleInfoParams.serverName;
            String serverId = roleInfoParams.serverId;
            String roleLevel = roleInfoParams.roleLevel;
            String power = roleInfoParams.power;
            String vipLevel = roleInfoParams.vipLevel;
            int event = roleInfoParams.event;
            String message = "上报角色信息：\n" +
                    "角色名：" + roleName + "\n" +
                    "角色ID：" + roleId + "\n" +
                    "服务器名：" + serverName + "\n" +
                    "服务器ID：" + serverId + "\n" +
                    "角色等级：" + roleLevel + "\n" +
                    "战力：" + power + "\n" +
                    "VIP等级：" + vipLevel + "\n" +
                    "event：" + event + "\n";
            SimpleHttpGetRequest httpRequest = new SimpleHttpGetRequest(new SimpleHttpGetRequest.OnHttpRequestCompleteListener() {
                @Override
                public void onHttpRequestComplete(String result) {
                    // 在这里处理 HTTP 请求的结果
                    try {
                        if (result != null) {
                            // 处理成功的情况
                            // result 包含服务器响应的内容
                            JSONObject jsonObject = new JSONObject(result);
                            int code = jsonObject.getInt("code");
                            String msg = jsonObject.getString("msg");
                            if (getLocalConfig(context).getChannel().equals("aggregation")) {
                                if (code == CONSTANT.SUCCESS) {
                                    AHSDKManager.showToast(context, String.format("上报成功\n%s", message));
                                } else {
                                    AHSDKManager.showToast(context, "上报失败\n" + msg);
                                }
                            } else {
                                getChannel().uploadRoleInfo(context, roleInfoParams);
                            }
                        } else {
                            // 处理失败的情况
                            if (getLocalConfig(context).getChannel().equals("aggregation")) {
                                AHSDKManager.showToast(context, "上报失败");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        if (getLocalConfig(context).getChannel().equals("aggregation")) {
                            AHSDKManager.showToast(context, "上报出错:" + e.getMessage());
                        }
                    }
                }
            });
            new Thread(new Runnable() {
                @Override
                public void run() {
                    httpRequest.execute("/v1.jh_report", roleInfoParams);
                }
            }).start();
        } else {
            LogUtils.error("请先初始化");
        }
    }



    @Override
    public void initApplication(Application application) {
        mContext = application;

        if (getChannel() != null) {
            getChannel().initApplication(application);
        } else {
            LogUtils.error("请先初始化");
        }
    }


    @Override
    public ILifeCycle getLifeCycle() {
        if (channel == null || getChannel().getLifeCycle() == null) {
            LogUtils.error("渠道未注册时,调用了获取渠道的生命周期对象");
            return defaultLifeCycle;
        }
        return getChannel().getLifeCycle();
    }

    public LocalConfig getLocalConfig(Context context) {
        if (localConfig == null) {
            // 读取配置文件
            Properties properties = ConfigUtils.loadConfigFromAssets(context);
            localConfig = ConfigBuilder.buildConfig(LocalConfig.class, properties);
        }
        return localConfig;
    }

    public IChannel getChannel() {
        if (channel == null) {
            channel = ChannelFactory.createChannel(getLocalConfig(mContext).getChannel());
        }
        return channel;
    }

    public ISDKListener getSDKListener() {
        return mISDKListener;
    }

    public static void showToast(Context context, String message) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
    }

    public MetaDataConfig getMetaDataConfig() {
        return metaDataConfig;
    }

    public void logout() {
        // TODO 暂时不需要登出接口，直接通知
        UserInfo.getInstance().setLoginResult(null);
        AHAOUiManager.getInstance().hideFloatView();
        mISDKListener.onLogoutResult(CONSTANT.SUCCESS, "登出成功");
    }
}
